import magpylib as magpy
import numpy as np
import matplotlib.pyplot as plt

# 定义大线圈（左、右各一个）
coil_large_left = magpy.current.Circular(
    current=1,  # 电流1A
    diameter=0.9,  # 直径900mm=0.9m
    nturns=38,     # 匝数38
    position=(-0.306, 0, 0)  # 左大线圈位置（间距612mm，中心在-0.306m处）
)
coil_large_right = magpy.current.Circular(
    current=1,
    diameter=0.9,
    nturns=38,
    position=(0.306, 0, 0)   # 右大线圈位置
)

# 定义小线圈（左、右各一个）
coil_small_left = magpy.current.Circular(
    current=1,
    diameter=0.328,  # 直径328mm=0.328m
    nturns=4,        # 匝数4
    position=(-0.306, 0, 0)  # 左小线圈与左大线圈共面同心
)
coil_small_right = magpy.current.Circular(
    current=1,
    diameter=0.328,
    nturns=4,
    position=(0.306, 0, 0)   # 右小线圈与右大线圈共面同心
)

# 组合所有线圈为系统
system = magpy.Collection(
    coil_large_left, coil_large_right,
    coil_small_left, coil_small_right
)

# 定义观测区域：以O为中心，直径200mm的球域（坐标范围-0.1m到0.1m）
xs = np.linspace(-0.1, 0.1, 50)
ys = np.linspace(-0.1, 0.1, 50)
zs = np.linspace(-0.1, 0.1, 50)

# 1. 绘制XOY平面（Z=0）的X分量磁场等高线
fig, ax = plt.subplots(figsize=(8, 6))
X, Y = np.meshgrid(xs, ys)
Bx = np.array([[system.getB((x, y, 0))[0] for x in xs] for y in ys])
contour = ax.contourf(X, Y, Bx, levels=20, cmap='viridis')
plt.colorbar(contour, label='Bx (T)')
ax.set_xlabel('X (m)')
ax.set_ylabel('Y (m)')
ax.set_title('XOY Plane - X-Component Magnetic Field')
plt.show()

# 2. 绘制沿X轴的磁场分布
Bx_xaxis = [system.getB((x, 0, 0))[0] for x in xs]
plt.figure(figsize=(8, 4))
plt.plot(xs, Bx_xaxis)
plt.xlabel('X (m)')
plt.ylabel('Bx (T)')
plt.title('X-Component Magnetic Field Along X-Axis')
plt.grid(True)
plt.show()

# （同理可绘制XOZ平面、YOZ平面，以及沿Y、Z轴的分布曲线）
